<?php

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\Order as OrderModel;
use app\api\model\Wxapp as WxappModel;
use app\common\library\wechat\WxPay;
use app\api\model\User;

/**
 * 用户订单管理
 * Class Order
 * @package app\api\controller\user
 */
class Order extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 我的订单列表
     * @param $dataType
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists($dataType)
    {
        $model = new OrderModel;
        $list = $model->getList($this->user['user_id'], $dataType);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 我的订单列表(工作订单：配送、服务)
     * @param $dataType
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function listsdelivery($dataType,$userType=2)
    {
        $model = new OrderModel;
        $list = $model->getListDelivery($this->user['user_id'], $dataType, $userType);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 订单详情信息
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail($order_id)
    {
        $order = OrderModel::getUserOrderDetail($order_id);
        return $this->renderSuccess(['order' => $order]);
    }

    /**
     * 取消订单
     * @param $order_id
     * @return array
     * @throws \Exception
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function cancel($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id);
        if ($model->cancel()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 发货：
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function delivery($order_id, $formId = "")
    {

        $model = OrderModel::getUserOrderDetail($order_id);

        #--测试：
        /*if ($this->user['user_id'] == 25) {
            dump($formId);halt(900);
        }*/

        if ($model->delivery()) {

            #--客户信息：
            $u_data = (new \app\api\model\User())->get(['user_id' => $model['user_id']]);

            #--定义发货提醒模板消息内容：
            $data = [
                'touser' => $u_data['open_id'],
                'template_id' => 'GDeWTBy-GsIFzelrwYKzWD6dXhMANkpL109brToPzgA',
                'url' => $web_url = "https://" . $_SERVER['SERVER_NAME'],
                'form_id' => ($model["prepay_id"]) ?: $formId,
                'topcolor' => "#FF0000",
                'data' => array(
                    #'first' => array('value' => "下单成功", 'color' => "#fc0101"),
                    'keyword1' => array('value' => $model['order_no'], 'color' => "#173177"), #--订单编号
                    'keyword2' => array('value' => $model["address"]["name"], 'color' => "#173177"), #--收货人
                    'keyword3' => array('value' => $model["address"]["phone"], 'color' => "#173177"), #--收货人电话
                    'keyword4' => array('value' => $this->user["phone"] ?: 18600650575, 'color' => "#173177"), #--配送员电话
                    'keyword5' => array('value' => $model["address"]["detail"], 'color' => "#173177"), #--目的地
                    'keyword6' => array('value' => '送货上门，您的订单已发货，请保持联系电话畅通，谢谢！', 'color' => "#173177"), #--配送方式
                    #'remark' => array('value' => "", 'color' => "#173177"),
                )
            ];
            #--推送：
            send_template_message($data);

            return $this->renderSuccess();

        } else {
            return $this->renderError($model->getError());
        }

    }

    /**
     * 送达：
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function reachOrder($order_id)
    {

        $model = OrderModel::getUserOrderDetail($order_id);

        if ($model->reachOrder(empty($model['b_id']))) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());

    }

    /**
     * 确认收货
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function receipt($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id);
        if ($model->receipt()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 服务接单
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function takeOrder($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id);
        if ($model->takeOrder()) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 服务完成
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function service($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id);
        if ($model->service($model["b_id"])) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError());
    }

    /**
     * 立即支付
     * @param $order_id
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function pay($order_id)
    {
        // 订单详情
        $order = OrderModel::getUserOrderDetail($order_id);
        // 判断商品状态、库存
        if (!$order->checkGoodsStatusFromOrder($order['goods'])) {
            return $this->renderError($order->getError());
        }
        // 发起微信支付
        $wxConfig = WxappModel::getWxappCache();
        // halt($wxConfig);
        $WxPay = new WxPay($wxConfig);
        $wxParams = $WxPay->unifiedorder($order['order_no'], $this->user['open_id'], $order['pay_price']);
        return $this->renderSuccess($wxParams);
    }

    /**
     * 保存用户form_id
     * @form_id int
     * @return array
     */
    public function saveFormId($formId = "")
    {

        #--获取即更新：
        if ($formId && $formId != "the formId is a mock one") {

            #if ($this->user['user_id']==25) {}
            (new User)->addFormId($this->user['user_id'], $formId);
            #User::update(['form_id' => Db::raw("if(form_id is null," . $formId . ",CONCAT(form_id,','," . $formId . "))")], ['user_id' => $this->user['user_id']], true);
            #User::update(['form_id' => $formId], ['user_id' => $this->user['user_id']], true);

        }

        return $this->success(($formId)?'保存成功':'未获取');

    }


}
